<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="学期" prop="semesterId">
        <el-select v-model="queryParams.semesterId" placeholder="请选择学期" clearable @change="handleSemesterChange">
          <el-option
            v-for="semester in semesterOptions"
            :key="semester.semesterId"
            :label="semester.semesterName"
            :value="semester.semesterId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="查询类型" prop="queryType">
        <el-select v-model="queryParams.queryType" placeholder="查询类型" clearable @change="handleQueryTypeChange">
          <el-option label="班级课表" value="class" />
          <el-option label="教师课表" value="teacher" />
          <el-option label="教室课表" value="classroom" />
          <el-option label="学生课表" value="student" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="queryParams.queryType === 'class'" label="班级" prop="classId">
        <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable>
          <el-option
            v-for="classItem in classOptions"
            :key="classItem.classId"
            :label="classItem.className"
            :value="classItem.classId"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="queryParams.queryType === 'teacher'" label="教师" prop="teacherId">
        <el-select v-model="queryParams.teacherId" placeholder="请选择教师" clearable>
          <el-option
            v-for="teacher in teacherOptions"
            :key="teacher.userId"
            :label="teacher.userName"
            :value="teacher.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="queryParams.queryType === 'classroom'" label="教室" prop="classroomId">
        <el-select v-model="queryParams.classroomId" placeholder="请选择教室" clearable>
          <el-option
            v-for="classroom in classroomOptions"
            :key="classroom.classroomId"
            :label="classroom.classroomName"
            :value="classroom.classroomId"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="queryParams.queryType === 'student'" label="学生" prop="studentId">
        <el-select v-model="queryParams.studentId" placeholder="请选择学生" clearable filterable>
          <el-option
            v-for="student in studentOptions"
            :key="student.studentId"
            :label="student.studentName + ' - ' + student.studentCode"
            :value="student.studentId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['academic:courseSchedule:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-date"
          size="mini"
          @click="toggleCalendarView"
        >{{ calendarView ? '列表视图' : '日历视图' }}</el-button>
      </el-col>
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>

    <div class="course-schedule-container">
      <div class="schedule-header">
        <h3>{{ currentSemesterName }} - 课表</h3>
      </div>
      <div class="schedule-table">
        <el-table
          :data="scheduleData"
          border
          style="width: 100%"
          :span-method="objectSpanMethod"
          v-loading="loading"
        >
          <el-table-column prop="weekday" label="星期" width="80" align="center">
            <template slot-scope="scope">
              {{ formatWeekday(scope.row.weekday) }}
            </template>
          </el-table-column>
          <el-table-column prop="period" label="节次" width="80" align="center">
            <template slot-scope="scope">
              {{ formatPeriod(scope.row.period) }}
            </template>
          </el-table-column>
          <el-table-column prop="courseName" label="课程名称" align="center" />
          <el-table-column prop="teacherName" label="教师" width="100" align="center" />
          <el-table-column prop="classroomName" label="教室" width="100" align="center" />
          <el-table-column prop="className" label="班级" width="100" align="center" />
          <el-table-column prop="weekType" label="周次" width="80" align="center">
            <template slot-scope="scope">
              {{ formatWeekType(scope.row.weekType) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 日历视图 -->
    <calendar-detail
      v-if="calendarView"
      :schedule-data="scheduleData"
      :semester-name="currentSemesterName"
      @week-change="handleWeekChange"
    />
  </div>
</template>

<script>
import { listCourseSchedule, getCourseScheduleBySemester, getTeacherSchedule, getClassSchedule, getClassroomSchedule, getStudentSchedule } from "@/api/academic/courseSchedule";
import { getSemesterOptions } from "@/api/academic/semester";
import CalendarDetail from "./calendar-detail";

export default {
  name: "CourseSchedule",
  components: {
    CalendarDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 学期选项
      semesterOptions: [],
      // 班级选项
      classOptions: [],
      // 教师选项
      teacherOptions: [],
      // 教室选项
      classroomOptions: [],
      // 学生选项
      studentOptions: [],
      // 查询参数
      queryParams: {
        semesterId: null,
        queryType: 'class',
        classId: null,
        teacherId: null,
        classroomId: null,
        studentId: null
      },
      // 课表数据
      scheduleData: [],
      // 当前学期名称
      currentSemesterName: '',
      // 合并单元格的数据
      spanData: [],
      // 是否显示日历视图
      calendarView: false
    };
  },
  created() {
    this.getSemesterOptions();
    this.getOtherOptions();
  },
  methods: {
    /** 获取学期选项 */
    getSemesterOptions() {
      getSemesterOptions().then(response => {
        this.semesterOptions = response.data;
        if (this.semesterOptions.length > 0) {
          this.queryParams.semesterId = this.semesterOptions[0].semesterId;
          this.currentSemesterName = this.semesterOptions[0].semesterName;
          this.getList();
        }
      });
    },
    /** 获取班级、教师、教室、学生选项 */
    getOtherOptions() {
      // 这里应该从相应的API获取数据，暂时使用模拟数据
      this.classOptions = [
        { classId: 1, className: '计算机一班' },
        { classId: 2, className: '计算机二班' },
        { classId: 3, className: '软件工程一班' }
      ];
      this.teacherOptions = [
        { userId: 1, userName: '张老师' },
        { userId: 2, userName: '李老师' },
        { userId: 3, userName: '王老师' }
      ];
      this.classroomOptions = [
        { classroomId: 1, classroomName: 'A101' },
        { classroomId: 2, classroomName: 'A102' },
        { classroomId: 3, classroomName: 'B201' }
      ];
      this.studentOptions = [
        { studentId: 1, studentName: '张三', studentCode: '2023001' },
        { studentId: 2, studentName: '李四', studentCode: '2023002' },
        { studentId: 3, studentName: '王五', studentCode: '2023003' }
      ];
    },
    /** 查询课表列表 */
    getList() {
      if (!this.queryParams.semesterId) {
        this.$modal.msgWarning("请先选择学期");
        return;
      }

      this.loading = true;
      
      let apiCall;
      switch (this.queryParams.queryType) {
        case 'teacher':
          if (!this.queryParams.teacherId) {
            this.loading = false;
            return;
          }
          apiCall = getTeacherSchedule(this.queryParams.teacherId, this.queryParams.semesterId);
          break;
        case 'class':
          if (!this.queryParams.classId) {
            this.loading = false;
            return;
          }
          apiCall = getClassSchedule(this.queryParams.classId, this.queryParams.semesterId);
          break;
        case 'classroom':
          if (!this.queryParams.classroomId) {
            this.loading = false;
            return;
          }
          apiCall = getClassroomSchedule(this.queryParams.classroomId, this.queryParams.semesterId);
          break;
        case 'student':
          if (!this.queryParams.studentId) {
            this.loading = false;
            return;
          }
          apiCall = getStudentSchedule(this.queryParams.studentId, this.queryParams.semesterId);
          break;
        default:
          apiCall = getCourseScheduleBySemester(this.queryParams.semesterId);
      }

      apiCall.then(response => {
        this.scheduleData = response.data;
        this.processSpanData();
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 处理合并单元格数据 */
    processSpanData() {
      // 这里可以实现合并相同课程的单元格逻辑
      this.spanData = [];
    },
    /** 合并单元格方法 */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 返回合并单元格的规则
      return {
        rowspan: 1,
        colspan: 1
      };
    },
    /** 学期变化处理 */
    handleSemesterChange(value) {
      const semester = this.semesterOptions.find(s => s.semesterId === value);
      this.currentSemesterName = semester ? semester.semesterName : '';
      this.getList();
    },
    /** 查询类型变化处理 */
    handleQueryTypeChange() {
      this.resetQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.classId = null;
      this.queryParams.teacherId = null;
      this.queryParams.classroomId = null;
      this.queryParams.studentId = null;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/academic/courseSchedule/export', {
        ...this.queryParams
      }, `course_schedule_${new Date().getTime()}.xlsx`);
    },
    /** 格式化星期 */
    formatWeekday(weekday) {
      const weekdays = ['', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
      return weekdays[weekday] || weekday;
    },
    /** 格式化节次 */
    formatPeriod(period) {
      const periods = {
        1: '第1节',
        2: '第2节',
        3: '第3节',
        4: '第4节',
        5: '第5节',
        6: '第6节',
        7: '第7节',
        8: '第8节'
      };
      return periods[period] || period;
    },
    /** 格式化周次类型 */
    formatWeekType(weekType) {
      const weekTypes = {
        1: '单周',
        2: '双周',
        3: '全周'
      };
      return weekTypes[weekType] || weekType;
    },
    
    /** 切换日历视图 */
    toggleCalendarView() {
      this.calendarView = !this.calendarView;
    },
    
    /** 处理周变化 */
    handleWeekChange(weekRange) {
      // 可以根据需要重新加载特定周的数据
      console.log('周变化:', weekRange);
    }
  }
};
</script>

<style scoped>
.course-schedule-container {
  margin-top: 20px;
}

.schedule-header {
  text-align: center;
  margin-bottom: 20px;
}

.schedule-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
}

.schedule-table {
  background: #fff;
  border-radius: 4px;
  overflow: hidden;
}
</style>